package com.ruoyi.patient.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.patient.entity.LoginPatient;
import com.ruoyi.patient.entity.PatientServedVO;
import com.ruoyi.patient.entity.ServedBody;
import com.ruoyi.patient.entity.ServedRequest;
import com.ruoyi.patient.service.PatientTokenService;
import com.ruoyi.patient.service.ServedService;
import com.ruoyi.patient.utils.PatientTokenFilter;
import com.ruoyi.service.domain.ServiceServed;
import com.ruoyi.service.service.IServiceServedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 被服务人控制类
 *
 * @author ZDL
 */

@RestController
@RequestMapping("/appPatient/appPatientServed")
public class PatientServedController {

    @Autowired
    private IServiceServedService serviceServedService;

    @Autowired
    private ServedService servedService;

    @Autowired
    private PatientTokenService tokenService;

    @Autowired
    private PatientTokenFilter patientTokenFilter;


    /**
     * 被服务人新增方法
     *
     * @param servedRequest 被服务人请求体
     * @return 结果
     */
    @PostMapping("/addServed")
    public AjaxResult addServesd(@RequestBody ServedRequest servedRequest, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }
            if(servedRequest.getName() == null || servedRequest.getIdCard() == null || servedRequest.getPhone() == null || servedRequest.getAddress() == null) {
                return AjaxResult.warn("信息错误");
            }
            if (servedRequest.getRelation() == null || "".equals((servedRequest.getRelation()).trim())){
                servedRequest.setRelation("本人");
            }
            //verifyCode 验证手机验证码 调用其他接口

            if (servedRequest.getServeId() == null){
                if (servedService.addServed(servedRequest, oldPatient)) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("flag", true);
                    return AjaxResult.success("添加成功", data);
                } else {
                    Map<String, Object> data = new HashMap<>();
                    data.put("flag", false);
                    return AjaxResult.error("添加失败", data);
                }
            }else{
                ServiceServed oldServed = serviceServedService.selectServiceServedByServedId(servedRequest.getServeId());
                if (oldServed == null){
                    return AjaxResult.warn("信息错误");
                }
                if (servedService.addServed(servedRequest, oldPatient)) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("flag", true);
                    return AjaxResult.success("修改成功", data);
                } else {
                    Map<String, Object> data = new HashMap<>();
                    data.put("flag", false);
                    return AjaxResult.error("修改失败", data);
                }
            }


        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 被服务人修改方法//不使用
     *
     * @param servedBody 被服务人操作信息
     * @return 结果
     */
    @PostMapping("/updateServed")
    public AjaxResult updateServed(@RequestBody ServedBody servedBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }

            if (!"1".equals(servedBody.getFlag())) {
                return AjaxResult.warn("操作无效");
            }
            if(servedBody.getServedAddress() == null || servedBody.getServedIdnumber() == null || servedBody.getServedName() == null) {
                return AjaxResult.warn("信息错误");
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient.getUserId() == null || oldPatient.getUserId() != servedBody.getServedUserid()) {
                return AjaxResult.warn("用户信息错误");
            }


            ServiceServed oldServed = serviceServedService.selectServiceServedByServedId(servedBody.getServedId());
            if(oldServed == null || oldServed.getServedUserid() != servedBody.getServedUserid()){
                return AjaxResult.warn("被服务人信息错误");
            }else{
                if (servedService.updateServed(servedBody, oldPatient)) {
                    return AjaxResult.success("修改成功");
                } else {
                    return AjaxResult.error("修改失败");
                }
            }

        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 被服务人删除方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/deleteServed")
    public AjaxResult deleteServed(@RequestBody Map<String, Long> reqBody, HttpServletRequest request) {
        try{
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }
            if(reqBody.get("serveId") == null){
                return AjaxResult.warn("信息错误");
            }

            ServiceServed oldServed = serviceServedService.selectServiceServedByServedId(reqBody.get("serveId"));
            if(oldServed == null || oldServed.getServedUserid() != oldPatient.getUserId() || oldServed.getServedDelFlag().equals("2")){
                return AjaxResult.warn("被服务人信息错误");
            }else{
                if (servedService.updateServed(oldServed, oldPatient)) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("flag", true);
                    return AjaxResult.success("删除成功", data);
                } else {
                    Map<String, Object> data = new HashMap<>();
                    data.put("flag", false);
                    return AjaxResult.error("删除失败", data);
                }
            }

        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 被服务人查询方法
     *
     * @param
     * @return 结果
     */
    @GetMapping("/getServed")
    public AjaxResult getServed(HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }

            List<PatientServedVO> servedList = servedService.getServed(oldPatient);
            return AjaxResult.success("获取成功", servedList);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 被服务人发送手机验证码方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/sendCode")
    public AjaxResult sendCode(@RequestBody Map<String, String> reqBody, HttpServletRequest request) {
        try {
            String phone = reqBody.get("phone");

            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }

            Boolean result = servedService.sendCode(phone, oldPatient);
            //String result = servedService.sendCode(phone, oldPatient);

            //String code = "500";
            //Pattern pattern = Pattern.compile("code=(\\d+)");
            //Matcher matcher = pattern.matcher(result);
            //if (matcher.find()) {
            //    code = matcher.group(1); // 获取括号中的数字
            //}
            //String message = "用户验证码请求频繁，请稍后再试！";
            //pattern = Pattern.compile("(\\d+)msg=(\\d+)");
            //matcher = pattern.matcher(result);
            //if (matcher.find()) {
            //    message = matcher.group(1);
            //}

            //else if ("104".equals(code)){
            //    return AjaxResult.error("用户验证码请求频繁，请稍后再试！");
            //}
            if(result){
                return AjaxResult.success("发送成功");
            }else{
                return AjaxResult.error("发送失败");
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 被服务人验证手机验证码方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/verifyCode")
    public AjaxResult verifyCode(@RequestBody Map<String, String> reqBody, HttpServletRequest request) {
        try {
            String code = reqBody.get("code");
            String phone = reqBody.get("phone");

            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }

            Integer result = servedService.verifyCode(code, phone, oldPatient);
            if(result == 0){
                return AjaxResult.success("验证成功");
            }else if(result == 2){
                return AjaxResult.error("验证码已过期，请重新发送");
            }else{
                return AjaxResult.error("验证码错误，请检查或重新发送");
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

}
